<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */
class managestoreController extends appRain_Base_Core
{

    public $name = 'manageStore';
    public $dispatch =  Array( 
        'preDispatchExclude'=>array(),
        'postDispatchExclude'=>array()
	);
    
    public function __preDispatch(){}

    public function indexAction($action=null, $id=null, $page=1)
    { 
    }

    public function productsAction($action=NULL,$id=NULL)
    {
        $this->setAdminTab('catalog');
		if(in_array($action,array('add','update','view'))){
			$this->set('admin_content_clear_length',true);
		}

		$product = App::InformationSet('product')->findByid($id);	
		$this->set('product',$product);	
		
		if($action=='delete'){
			$this->deleteProduct($product);
			$this->redirect("/managestore/products/");
		}
	
		
		if(!empty($this->data)){
			$attributevalue = '';		
			$imageThumbFile = App::Component('appStore')->Helper('Common')->getProductValue($product,'imagethumb');
			if(!empty($this->data['Product']['imagethumb']['name'])){
				$imagethumb = App::Utility()->upload($this->data['Product']['imagethumb'],App::Config()->filemanagerDir("/"));
				$imageThumbFile = $imagethumb['file_name'];
			}
			
			$imageFile = App::Component('appStore')->Helper('Common')->getProductValue($product,'image');
			if(!empty($this->data['Product']['image']['name'])){
			
				$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$imageFile);				
				$image = App::Utility()->upload($this->data['Product']['image'],App::Config()->filemanagerDir("/"));
				$imageFile = $image['file_name'];
			}

			$downloadfilepath = $this->data['Product']['downloadfilepath'];
			if(!empty($this->data['Product']['downfilepath_file_input']['name'])){
				if(isset($product['downloadfilepath']) && !empty($product['downloadfilepath'])){
					$this->unlinkPrevFile(App::Config()->rootDir("/component/appstore/virtualproductfiles/"),$product['downloadfilepath']);
				}
				$downloadfilepathimage = App::Utility()->upload($this->data['Product']['downfilepath_file_input'],App::Config()->rootDir("/component/appstore/virtualproductfiles/"));
				$downloadfilepath = $downloadfilepathimage['file_name'];
			}
	
			$imagelist = App::Component('appStore')->Helper('Common')->getProductValue($product,'imagelist');
			if($this->data['Product']['slidetype'] == 'Zoom'){
				if(!empty($this->data['Product']['imagelist']['name'])){
					if( $product['slidetype'] != 'Zoom'){
						$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$imagelist);	
						$imagelist = '';
					}
					foreach($this->data['Product']['imagelist']['name'] as $key=>$row){
						$imgObj = array(
							'name' => $this->data['Product']['imagelist']['name'][$key],
							'type' => $this->data['Product']['imagelist']['type'][$key],
							'tmp_name' => $this->data['Product']['imagelist']['tmp_name'][$key],
							'error' => $this->data['Product']['imagelist']['error'][$key],
							'size' => $this->data['Product']['imagelist']['size'][$key]
						);
						$tmp = App::Utility()->upload($imgObj,App::Config()->filemanagerDir("/"));		
						
						App::Load("Helper/Utility")
							->createThumb(
								App::Config()->filemanagerDir("/{$tmp['file_name']}"),
								App::Config()->filemanagerDir("/small_{$tmp['file_name']}"),450,450
							);
						App::Load("Helper/Utility")
							->createThumb(
								App::Config()->filemanagerDir("/{$tmp['file_name']}"),
								App::Config()->filemanagerDir("/thumb_{$tmp['file_name']}"),90,90
							);							
						$Imagelist[] = "thumb_{$tmp['file_name']}";								
						$Imagelist[] = "small_{$tmp['file_name']}";								
						$Imagelist[] = $tmp['file_name'];
					}
					
					if($imagelist != ''){
						$imagelist = $imagelist . "," . implode(',',$Imagelist);
					}
					else {
						$imagelist = implode(',',$Imagelist);
					}
				}
			}
			else {
				if(!empty($this->data['Product']['largeimage']['name'])){
					$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$imagelist);	
					$largeimage = App::Utility()->upload($this->data['Product']['largeimage'],App::Config()->filemanagerDir("/"));
					$imagelist = $largeimage['file_name'];
				}
			}
			
			$gallerylist = App::Component('appStore')->Helper('Common')->getProductValue($product,'galleryimagelist');
			if(!empty($this->data['Product']['gallerylist']['name'])){
				$Imagelist = array();
				foreach($this->data['Product']['gallerylist']['name'] as $key=>$row){
					$imgObj = array(
						'name' => $this->data['Product']['gallerylist']['name'][$key],
						'type' => $this->data['Product']['gallerylist']['type'][$key],
						'tmp_name' => $this->data['Product']['gallerylist']['tmp_name'][$key],
						'error' => $this->data['Product']['gallerylist']['error'][$key],
						'size' => $this->data['Product']['gallerylist']['size'][$key]
					);
					$tmp = App::Utility()->upload($imgObj,App::Config()->filemanagerDir("/"));		
					
					$Imagelist[] = $tmp['file_name'];
				}
				
				if($gallerylist != ''){
					$gallerylist = $gallerylist . "," . implode(',',$Imagelist);
				}
				else {
					$gallerylist = implode(',',$Imagelist);
				}				
			}
						
			$attributevalue = App::Component('appStore')->Helper('Common')->getProductValue($product,'attributevalue');

			if(!empty($this->data['Product']['attributegroup'])){
				
				if(!empty($attributevalue)){
					$PrevArr = unserialize($attributevalue);
				}

				$Group = App::Component('appStore')->Helper('Common')->getAttributeGroupById($this->data['Product']['attributegroup']);
				if(!empty($Group['object'])){
					$AttributeateValue = array();
					$AttributeateFields = array();
					foreach($Group['object'] as $key=>$row){
						if(!empty($row['key'])){
							$Index = $row['key'];
							$AttributeateValue[$Index]['title'] = $row['title'];
							$AttributeateValue[$Index]['value']  = '';
							$FieldPost = $this->data['Product']["prod_attr_{$key}"];
							if(in_array(strtolower($row['type']),array('image','file'))){							
								$AttributeateValue[$Index]['value'] = isset($PrevArr[$row['key']]['value']) ? $PrevArr[$row['key']]['value'] : '';
								if(!empty($FieldPost['name'])){
									$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$AttributeateValue[$Index]['value']);
									$tmp = App::Utility()->upload($FieldPost,App::Config()->filemanagerDir("/"));
									$AttributeateValue[$Index]['value'] = $tmp['file_name'];
								}						}
							else {
								$AttributeateValue[$Index]['value'] = $FieldPost;
							}	
						}		
					}		
					$attributevalue = serialize($AttributeateValue);
				}
			}	
			
			$relatedproduct= '';
			if(!empty($this->data['Product']['relatedproduct'])){
				$relatedproduct = implode(',',$this->data['Product']['relatedproduct']);
			}
			
			$prodObj = App::InformationSet('product')
				->setId($id)
				->setTitle($this->data['Product']['title'])
				->setShortdesc($this->data['Product']['shortdesc'])
				->setPromotext($this->data['Product']['promotext'])
				->setDescription($this->data['Product']['description'])
				->setFeatures($this->data['Product']['features'])
				->setCategory(implode(',',$this->data['Product']['category']))
				->setType($this->data['Product']['type'])
				->setShippingmethod($this->data['Product']['shippingmethod'])
				->setDownloadfilepath($downloadfilepath)
				->setSupplierprice($this->data['Product']['supplierprice'])
				->setOldprice($this->data['Product']['oldprice'])
				->setPrice($this->data['Product']['price'])
				->setQty($this->data['Product']['qty'])
				->setCriticalqty($this->data['Product']['criticalqty'])
				->setAttributegroup($this->data['Product']['attributegroup'])
				->setAttributeValue($attributevalue)
				->setSlidetype($this->data['Product']['slidetype'])
				->setNote($this->data['Product']['note'])
				->setRedirectafteradd2card($this->data['Product']['redirectafteradd2card'])
				->setRelatedproduct($relatedproduct)
				->setPagetitle($this->data['Product']['pagetitle'])
				->setPagekeys($this->data['Product']['pagekeys'])
				->setPagedec($this->data['Product']['pagedec'])
				->setImagethumb($imageThumbFile)
				->setImage($imageFile)
				->setImagelist($imagelist)
				->setGalleryImagelist($gallerylist)
				->Save();
			App::Module('Notification')->Push('Product has been saved successfully');	
			
			$anchor = '';
			if(isset($this->post['Anchor'])){
				$anchor = key($this->post['Anchor']);
			}
			
			$this->redirect("/managestore/products/update/" . $prodObj->getId() . "#{$anchor}");
		}
		
		$this->set('action',$action);
		$this->set('id',$id);		
    }
	
	private function deleteProduct($Product=null){
		if(empty($Product)){
			App::Module('Notification')->Push('Sorry! Product not found.','Warning');
			return ;
		}
		
		$Items = App::Model('Item')->findByProductid($Product['id']);
		if(!empty($Items)){
			App::Module('Notification')->Push('Sorry! Could not delete product, At atleat one iteam has been purchased.','Warning');
			App::Module('Notification')->Push('you can chnage status to deactivate it.','Notice');
			
		}

		// Clear Resouce	
		$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$Product['imagethumb']);
		$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$Product['image']);
		$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$Product['imagelist']);
		
		App::InformationSet('product')->Delete($Product['id']);
		App::Module('Notification')->Push('Product has been remove successfully.');
		
	}
	
	private function unlinkPrevFile($path=null,$listofname=null){
		if(empty($listofname)){
			return ;
		}
		
		$array = explode(',',$listofname);
		foreach($array as $name){
			$filePath = $path . $name;
			if(file_exists($filePath) && is_writable($filePath)){
				@unlink($filePath);
			}
		}
		
	}
	
	public function productattributesAction($action=null,$id=null){
		$this->setAdminTab('catalog');

		if(!empty($this->data)){
			if(in_array($action,array('addgroup','editgroup'))){
				if(!isset($this->data['AttributeGroup']['name'])){
					App::Module('Notification')->Push('Please enter a group name','Error');
					$this->redirect("/managestore/productattributes/addgroup");
					exit;
				}
				else {
					$obj = App::InformationSet('attributegroup')
						->setId($id)
						->setName($this->data['AttributeGroup']['name'])
						->Save();
					App::Module('Notification')->Push('Group added successfully');	
					$this->redirect("/managestore/productattributes/edit/" . $obj->getId());
				}
			}
			else if($action == 'editattribute'){ 
					$Group = App::Component('appStore')
						->Helper('Common')
						->setId($id)
						->setSequence($this->get['seq'])
						->updateAttributeObject($this->data['Field'],$action);
					$this->redirect("/managestore/productattributes/{$action}/" . $id . '?seq=' . $this->get['seq']);	
			}
			else if ($action == 'addfield'){
				$Group = App::Component('appStore')->Helper('Common')->getAttributeGroupById($id);
				$array = empty($Group['object']) ? Array() : $Group['object'];
				$this->data['Field']['key'] = App::Component('appStore')->Helper('Common')->getAttributeKey();
				$array[] = $this->data['Field'];
				$obj = App::InformationSet('attributegroup')
						->setId($id)
						->setObject(serialize($array))
						->Save();
				App::Module('Notification')->Push('Group saved successfully');		
				$this->redirect("/managestore/productattributes/edit/" . $obj->getId());
			}
		}
		
		if($action == 'deleteattribute'){
			$Group = App::Component('appStore')
				->Helper('Common')
				->setId($id)
				->updateAttributeObject($this->get['seq'],'remove');
				
			App::Module('Notification')->Push('Attribute has been removed successfully');		
			$this->redirect("/managestore/productattributes/edit/" . $id);	
		}
		
		$groupList = App::InformationSet('attributegroup')->paging("1 ORDER BY id DESC");
		$this->set('groupList',$groupList);
		
		$this->set('action',$action);
		$this->set('id',$id);		
	}
	
	
	public function getproductdataAction($id=null,$pid=null){
		$this->setAdminTab('catalog');
		$this->layout = 'empty';
		if(isset($id)){		
			echo App::Component('appStore')->Helper('Common')->getAttributeHtmlBox($id,$pid);
		}
	}
	
	public function deleteimageAction(){
		$this->setAdminTab('catalog');
		$this->layout = 'empty';
		$data = App::Module('Cryptography')->jsonDecode($this->post['data']);
		if(empty($data)){
			return ;
		}
		
		$pid = isset($data['pid']) ? $data['pid'] : '';
		$action = isset($data['action']) ? $data['action'] : '';		
		$product = App::InformationSet('product')->findById($pid);
		switch($action){
			case 'attributefile':
				$attributevalue = unserialize($product['attributevalue']);
				$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$attributevalue[$data['key']]['value']);	
				unset($attributevalue[$data['key']]);
				$obj = App::InformationSet('product')->setId($pid)
					->setAttributevalue(serialize($attributevalue))
					->Save();
				break;
			case 'imagelist':
				$list = explode(',',$product['imagelist']);
				$newlist = array();
				foreach($list as $img){
					if($data['name']== $img){
						$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$img);	
					}
					else{
						$newlist[] = $img;
					}
				}
				$obj = App::InformationSet('product')->setId($pid)
					->setImagelist(implode(',',$newlist))
					->Save();
				break;
			case 'galleryimagelist':
				$list = explode(',',$product['galleryimagelist']);
				$newlist = array();
				foreach($list as $img){
					if($data['name']== $img){
						$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$img);	
					}
					else{
						$newlist[] = $img;
					}
				}
				$obj = App::InformationSet('product')->setId($pid)
					->setGalleryimagelist(implode(',',$newlist))
					->Save();
				break;
				
			default:
				$img_name = isset($product[$action]) ? $product[$action] : '';
				if(!empty($product[$action])){
					$this->unlinkPrevFile(App::Config()->filemanagerDir("/"),$img_name);	
					$fx = "set{$action}";
					$obj = App::InformationSet('product')->setId($pid)
						->$fx('')
						->Save();
				}
		}
	}
	
	public function commentAction($action=null, $id = null)
    {
        // Set Admin Tab
        $this->setAdminTab('catalog');

        // Update the post if
        // the action is set to 'update'
        if($action == 'update'){

            if(!empty($this->data)){
			
                $this->data['StoreComment']['id'] = $id;
                $this->data['StoreComment']['dated'] = date('Y-m-d H:i:s',strtotime("{$this->data['StoreComment']['dated']['year']}-{$this->data['StoreComment']['dated']['month']}-{$this->data['StoreComment']['dated']['day']} {$this->data['StoreComment']['dated']['hour']}:{$this->data['StoreComment']['dated']['munite']}:{$this->data['StoreComment']['dated']['second']}"));
				App::Model('StoreComment')->Save($this->data);
				App::Module('Notification')->push("Comment updates successfully");
                $this->redirect("/managestore/comment");
                exit;
            }

            $comment = App::Model('StoreComment')->findById($id);
            $this->set("comment",$comment);
            $this->set('id',$id);
        }
        else{
            // Fetch all comments form 'Comment' model
            // and assign to template
            $comments = App::Model('StoreComment')->paging("1 ORDER BY id DESC");
            $this->set("comments",$comments);
        }

        $this->set("action",$action);
    }	
	
	

    /**
     * Manage Order data from admin panel
     */
    public function ordersAction($action=NULL,$id=NULL)
    {
        $this->setAdminTab('catalog');

        if($action=='view') {
            if(!empty($this->data)) {
			
				$Order = App::Model('Order')->findById($id);
				$prevstatus = $Order['paymentstatus'];	
                $this->data['Order']['id'] = $id;				
                $obj = App::Model('Order')->Save($this->data);
				
				if($prevstatus != $this->data['Order']['paymentstatus'])
				{
					App::Component('appStore')->Helper('Data')->adjustInventoryByOrder($id);
				}				
                $this->redirect("/managestore/orders");
                exit;
            }

            $oderdata = App::Model('Order')->findById($id);

        }
        else {
            $this->addons = Array('row_manager');
            $oderdata = App::Model('Order')->Paging("1 ORDER BY ID DESC");
        }

        $this->set('action',$action);
        $this->set('oderdata',$oderdata);
    }
	
	public function discountAction($action=null)
	{
		$this->setAdminTab('catalog');
		
		if($action == 'downloadcsv'){
			$List = App::InformationSet('discountcoupon')->findAll("1 ORDER BY ID ASC");			
			$filename = time() . '.csv';
			$path = BYTE_STREAM . DS . $filename;			
			$f1 = fopen($path, "w");
			fputs($f1,'"ID","BATCH NAME","CODE","AMOUNT","CAL METHOD","STATUS"' . "\n");
			foreach($List['data'] as $row){
				fputs($f1,'"');
				fputs($f1,"{$row['id']}");
				fputs($f1,'","');
				fputs($f1,"{$row['batchname']}");
				fputs($f1,'","');
				fputs($f1,"{$row['code']}");
				fputs($f1,'","');
				fputs($f1,"{$row['amount']}");
				fputs($f1,'","');
				fputs($f1,"{$row['calmethod']}");
				fputs($f1,'","');
				fputs($f1,"{$row['status']}");
				fputs($f1,'"' . "\n");			
			}
			App::Utility()->Download($path,null,'Discount_List_' . date('Y-m-d_H:i:s') . '.csv');
			unlink($path);
			exit;			
		}
		
		if($action == 'downloadxml'){
			$List = App::InformationSet('discountcoupon')->findAll("1 ORDER BY ID ASC");				
			$filename = time() . '.xml';
			$path = BYTE_STREAM . DS . $filename;			
			$f1 = fopen($path, "w");
			fputs($f1,"<?xml version=\"1.0\" encoding=\"cp866\" ?>\n");
			fputs($f1,"<Root>\n");
			foreach($List['data'] as $row){
				fputs($f1,"<Record>\n");
				fputs($f1,"\t<Id>{$row['id']}</Id>\n");
				fputs($f1,"\t<Batchname>{$row['batchname']}</Batchname>\n");
				fputs($f1,"\t<Code>{$row['code']}</Code>\n");
				fputs($f1,"\t<Amount>{$row['amount']}</Amount>\n");
				fputs($f1,"\t<Calmethod>{$row['calmethod']}</Calmethod>\n");
				fputs($f1,"\t<Status>{$row['status']}</Status>\n");
				fputs($f1,"</Record>\n");			
			}
			fputs($f1,"</Root>\n");
			App::Utility()->Download($path,null,'Discount_List_' . date('Y-m-d_H:i:s') . '.xml');			
			unlink($path);
			exit;
		}
		
		if($action == 'updatesetting'){
			App::Config()->setSiteInfo('enablediscountmodule',$this->data['DiscountCouponCode']['enablediscountmodule']);
			App::Config()->setSiteInfo('discountrndstart',$this->data['DiscountCouponCode']['discountrndstart']);
			App::Config()->setSiteInfo('discountrndend',$this->data['DiscountCouponCode']['discountrndend']);
			App::Config()->setSiteInfo('discountcodeconstant',$this->data['DiscountCouponCode']['discountcodeconstant']);
			App::Config()->setSiteInfo('discountcodeconstantpos',$this->data['DiscountCouponCode']['discountcodeconstantpos']);			
			App::Config()->setSiteInfo('discountcalculationphpblock',$this->data['DiscountCouponCode']['discountcalculationphpblock']);

			echo App::Load("Module/Cryptography")
                    ->jsonEncode(
                    array(
                        "_status" => "Success",
                        "_message" => "Updated successfully"
                    )
                );
			exit;
		}
		
		if($action == 'createbatch' and !empty($this->data)){	
		
            $qty = $this->data['DiscountCouponCode']['qty'];
			
			for($ii=1; $ii<=$qty; $ii++){
				
				$rnd4 = rand(App::Config()->Setting('discountrndstart','100000'), App::Config()->Setting('discountrndend','999999'));				
				$obj=App::InformationSet('discountcoupon')
					->setId(null)
					->setBatchname($this->data['DiscountCouponCode']['batchname'])
					->setAmount($this->data['DiscountCouponCode']['amount'])
					->setCalmethod($this->data['DiscountCouponCode']['calmethod'])
					->Save();
					
				$code = App::Config()->Setting('discountcodeconstant','') . $obj->getId() . $rnd4;
				if(strtolower(App::Config()->Setting('discountcodeconstantpos','Left')) != 'left'){
					$code = $obj->getId() . $rnd4 . App::Config()->Setting('discountcodeconstant','');
				}
				
				$obj=App::InformationSet('discountcoupon')
					->setId($obj->getId())
					->setCode($code)
					->Save();
			}
			
			App::Module('Notification')->Push("Batch data created successfully");
			$this->redirect("/managestore/discount/createbatch");
		}		
		
		$List = App::InformationSet('discountcoupon')->paging("1 ORDER BY ID DESC",50);
		$this->set('List',$List);
	}	
	
	public function shippingroleAction($action=null,$id=null){
		$this->setAdminTab('catalog');

		if(isset($id)){
			$Roles = App::CategorySet('shippingrole')->findById($id);
		}
		else{
			$Roles = App::CategorySet('shippingrole')->findAll();
		}
		$this->set('Roles',$Roles);
		
		if(!empty($this->data)){
			App::Model('Category')->setId($id)
				->setDescription(serialize($this->data))
				->Save();
			App::Module('Notification')->Push("Updated successfully");
			$this->redirect("/managestore/shippingrole/update/{$id}");
		}
		
		$this->set('action',$action);
		$this->set('id',$id);
	}	
}
